<template>
  <div>
    <FormPanel
      ref="from"
      :list="formList"
      :formType="type"
      @formChange="changeHandle"
      :isSubmitBtn="false"
      labelWidth="110" />
    <BreakSpace v-if="type!=='add'" label="更新进度" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable v-if="type!=='add'"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      columnsRef="jzySeries"
      :onColumnsChange="columns => this.columns = columns"
    >
    </FilterTable>
    <BaseDialog :visible.sync="visbleVehicle" title="车辆选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-vehicle
        :rowData="formData"
        selectionType="single"
        @selectArr="selectVehicleFun"
        @closeDialog='visbleVehicle = false'></add-vehicle>
    </BaseDialog>
    <div class="dialogBottmView" >
      <el-button   @click="closeDialog">返 回</el-button>
      <el-button v-show="this.type==='add'"   @click="save()" :loading="saveLoading"  type="primary">保存</el-button>
    </div>
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import { demands,status,dealType,serious } from '@/pages/demandes/userDemandes/register/selectValue';
  import { region } from '@/api/cms-common/region';
  import { dosave, getSelectList,getHandleList } from '@/api/customerService/demandes/register';
  import {getDealerCompanyByCode} from '@/api/part/exchange/platform';
  import addVehicle from '@/pages/partsmanage/purchaseManage/purchaseSubmit/addVehicle';
  export default {
    name: 'demandesAdd',
    mixins: [dictionary,region],
    components:{addVehicle},
    props: {
      type: {
        type: String,
        default: 'add'
      },
      rowData: {
        type: Object,
        default: () => ({})
      }
    },
    created() {
      this.initProvince();
      this.init();
      this.findSlectValue()
    },
    data() {
      this.saveData=null;
      return {
        formData:{carvin:'',ronovin:''},
        visbleVehicle:false,
        fetchApi:getHandleList,
        columns: this.createTableColumns(),
        fetchParams:{demandsId:''},
        selectValue:{
          cityName:''
        },
        seriousList:[], // 严重程度
        saveLoading:false,
        formList: this.createTopFilterList(),
      };
    },
    methods: {
      createTableColumns () {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '工单号',
            dataIndex: 'demandsNo',
            sorter: true,
          },
          {
            title: '处理类型',
            dataIndex: 'handleType',
            sorter: true,
            dictItems:dealType
          },
          {
            title: '处理时间',
            dataIndex: 'handleTime',
            sorter: true,
            dateFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            title: '工单状态',
            dataIndex: 'demandsStatus',
            sorter: true,
            dictItems:status
          },
          {
            title: '备注来源',
            dataIndex: 'demandsOrigin',
            sorter: true,
          },
          {
            title: '备注内容',
            dataIndex: 'remark',
            sorter: true,
          },
          {
            title: '备注时间',
            dataIndex: 'remarkTime',
            sorter: true,
            dateFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            title: '当前责任人',
            dataIndex: 'responsible',
            sorter: true,
          },
          {
            title: '是否无效需求',
            dataIndex: 'wheterDemands',
            sorter: true,
            dictItems:demands
          }
        ]
      },
      init(){
        if (this.type === 'show') { //点击编辑按钮拿到这一行的值,并赋值
          this.fetchParams.demandsId= this.rowData.id
          this.formList.forEach(x => {
              x.initialValue = this.rowData[x.fieldName];
          });
          this.initFile(this.rowData)
          //初始化所在市，区
          if(this.rowData['provinceid']){
            this.initCity(this.rowData['provinceid'],false);
          }
          if(this.rowData['cityid']){
            this.initTown(this.rowData['cityid'],false);
          }
        }else if (this.type === 'add'){
          this.getuser();
          this.formList.find(item=>item.fieldName==='wheterDemands').hidden=true
        }
      },
      initFile(data){
        if (data){
          const fileArry = JSON.parse(data['extra'])
          fileArry.forEach(item=>{
            if (item.fileName=='file1'){
              this.formList.find(item=>item.fieldName==='file1').initialValue=[{name:item.name,url:item.url}]
            }else if(item.fileName=='file2'){
              this.formList.find(item=>item.fieldName==='file2').initialValue=[{name:item.name,url:item.url}]
            }else if(item.fileName=='file3'){
              this.formList.find(item=>item.fieldName==='file3').initialValue=[{name:item.name,url:item.url}]
            }else if(item.fileName=='file4'){
              this.formList.find(item=>item.fieldName==='file4').initialValue=[{name:item.name,url:item.url}]
            }else{
              this.formList.find(item=>item.fieldName==='file5').initialValue=[{name:item.name,url:item.url}]
            }
          })
        }
      },
      // 查询下拉选项的值
      findSlectValue(){
        getSelectList({}).then(response=>{
          this.formList.find(item=>item.fieldName==='demandsScenes').itemList=response.data.cjList
          this.formList.find(item=>item.fieldName==='infoSource').itemList=response.data.lyList
          this.formList.find(item=>item.fieldName==='model').itemList=response.data.cxList
        })
      },
      dealwithFile(data){
        let file = []
        if (data.file1.length>0){
          data.file1.forEach(item=>{
            file.push({
              fileName:'file1',
              name:item.name,
              url:item.url})
          })
        }
        if (data.file2.length>0){
          data.file2.forEach(item=>{
            file.push({
              fileName:'file2',
              name:item.name,
              url:item.url
            })
          })
        }
        if (data.file3.length>0){
          data.file3.forEach(item=>{
           file.push({
             fileName:'file3',
             name:item.name,
             url:item.url})
          })
        }
        if (data.file4.length>0){
         data.file4.forEach(item=>{
            file.push({
              fileName:'file4',
              name:item.name,
              url:item.url
            })
          })
        }
        if (data.file5.length>0){
          data.file5.forEach(item=>{
            file.push({
              fileName:'file5',
              name:item.name,
              url:item.url
            })
          })
        }
        return file;
      },
      async save(){
        let [err, data] = await this.$refs.from.GET_FORM_DATA();
        const file = await this.dealwithFile(data)
        Object.assign(data,{extra:JSON.stringify(file)})
        if (err){
          return false;
        }else{
          this.saveLoading=true
          Object.assign(data,this.selectValue)
          data.problemGarde =data.problemGarde[0] //严重程度
          await  dosave(data).then(res=>{
            if (res.resultCode === 200) {
              this.$notify.success({title: '提示信息',message:'保存成功!'});
              this.saveLoading=false
              // 重新加载
              this.closeDialog();
            }else {
              this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
              this.saveLoading=false
              this.closeDialog();
            }
          })
        }
      },
      //取消操作
      closeDialog() {
        this.$emit('close', { visible: false });
      },
      getuser(){
          // 获取当前登录人信息
        getDealerCompanyByCode({}).then(response=>{
            this.formList.find(res=>res.fieldName=='dealerCode').initialValue=response.data.dealerCode // 经销商代码
            this.formList.find(res=>res.fieldName=='dealerName').initialValue=response.data.dealerName // 经销商名称
          })
      },
      createTopFilterList() {
        const uploadParam = {
            selfCols: 1.5,
            type: 'UPLOAD_FILE',
            initialValue: '',
            upload: {
              actionUrl: '/api/file/oss/upload',
            }
          }
        return [{//2
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          initialValue:'',
          placeholder: '经销商代码',
          disabled:true
        },
          {//3
            type: 'INPUT',
            label: '经销商名称',
            fieldName: 'dealerName',
            initialValue: '',
            placeholder: '请输入',
            disabled: true,
            offsetRightCols:1
          },
          {//9
            type: 'SELECT',
            label: '场景',
            fieldName: 'demandsScenes',
            placeholder: '请选择',
            initialValue: '',
            itemList:  [],
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'MULTIPLE_CHECKBOX',
            label: '严重程度',
            limit:1,
            fieldName: 'problemGarde',
            initialValue: '',
            hidden:this.type==='show',
            offsetRightCols:1,
            itemList: [
              {
                text: '加急',
                value: '2',
                render: () => {
                  const value= this.formList.find(item=>item.fieldName==='problemGarde').initialValue[0]
                  if(value==='2'){
                    return (<div>加急 (加急:车辆无法使用)</div>);
                  }else {
                    return (<div>加急</div>);
                  }
                }
              },
              {
                text: '特急',
                value: '3',
                render: () => {
                  const value= this.formList.find(item=>item.fieldName==='problemGarde').initialValue[0]
                  if(value==='3'){
                    return (<div style='word-wrap : break-word'>特急 (特急: 1、设计身份特殊的重要人物 2、引起舆情传播 3、涉及人身伤亡、信息泄露或财产重大损失)</div>);
                  }else{
                    return (<div>特急</div>);
                  }
                }
              }
            ]
          },
          {//9
            type: 'SELECT',
            label: '严重程度',
            fieldName: 'problemGarde',
            placeholder: '请选择',
            initialValue: '',
            hidden:this.type==='add',
            itemList: serious ,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//17
            type: 'INPUT',
            label: '当前责任人',
            fieldName: 'responsible',
            placeholder: '请输入',
            initialValue: '',
            hidden:this.type==='add',
            maxlength:11,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//17
            type: 'INPUT',
            label: '用户姓名',
            fieldName: 'userName',
            placeholder: '请输入',
            initialValue: '',
            maxlength:11,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//14
            type: 'INPUT',
            label: '联系方式',
            fieldName: 'connectPhone',
            placeholder: '请输入',
            initialValue: '',
            maxlength:11,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'blur'
              },
              {
                pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                message: '请填写正确的手机格式',
                trigger: 'blur'
              }
            ]
          },
          {//9
            type: 'SELECT',
            label: '车型',
            fieldName: 'model',
            placeholder: '请选择',
            initialValue: '',
            itemList:  [],
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//10
            type: 'SELECT',
            label: '省份',
            fieldName: 'provinceid',
            placeholder: '请选择',
            initialValue: "",
            itemList:  [],
            change: (value) => {
              this.initCity(value)
            },
            rules: [{
              required: true,
              message: '必填',
              trigger: 'change'
            }]
          },
          {//11
            type: 'SELECT',
            label: '城市',
            fieldName: 'cityid',
            placeholder: '请选择',
            initialValue: "",
            itemList: [],
            change: (value) => {
              this.initTown(value)
            },
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//12
            type: 'SELECT',
            label: '县区',
            fieldName: 'districtid',
            placeholder: '请选择',
            initialValue: "",
            itemList:  [],
            change: (value) => {
              this.initDistrict(value)
            }
          },
          {//2
            type: 'INPUT',
            label: 'VIN',
            fieldName: 'vin',
            initialValue:'',
            readonly:true,
            unitRender: () => {
              return (
                <div>
                <el-button icon="el-icon-search" onClick={() => this.openvehicle()}></el-button>
              <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSelectModel()}></el-button>
              </div>
            );
            }
          },
          {//9
            type: 'SELECT',
            label: '信息来源',
            fieldName: 'infoSource',
            placeholder: '请选择',
            initialValue: '',
            hidden:true,
            itemList:  [],
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'SELECT',
            label: '是否无效需求',
            fieldName: 'wheterDemands',
            placeholder: '请选择',
            hidden:false,
            initialValue: '',
            itemList: demands
          },
          {//22
            type: 'TEXT_AREA',
            label: '用户诉求详情',
            fieldName: 'userDemandsDetails',
            placeholder: '请输入',
            initialValue: '',
            maxlength:300,
            selfCols:3,
          },
          {//17
            type: 'INPUT',
            label: '备注',
            fieldName: 'remark',
            placeholder: '请输入',
            initialValue: '',
            offsetRightCols:2,
            hidden:this.type==='add'
          },
          {
            label: '附件1',
            ...uploadParam,
            fieldName: 'file1',
          },
          {
            label: '附件2',
            ...uploadParam,
            fieldName: 'file2',
          },
          {
            label: '附件3',
            ...uploadParam,
            fieldName: 'file3',
          },
          {
            label: '附件4',
            ...uploadParam,
            fieldName: 'file4',
          },
          {
            selfCols: 1.5,
            type: 'UPLOAD_FILE',
            label: '附件5',
            fieldName: 'file5',
            initialValue: '',
            upload: {
              fileSize: 50,
              max: 1024 * 50,
              actionUrl: '/api/file/oss/upload'
            }
          },
        ]
      },
      changeHandle(val) {
        this.saveData=val;
      },
      //初始化所在省份
      async initProvince(){
        let pl = this.createRegionList();
        this.formList.find(item => item.fieldName === 'provinceid').itemList = pl;
      },
      //初始化所在市数据
      async initCity(provinceId,flag = true){
        if(flag){
          //清空市
          this.formList.find(item => item.fieldName === 'cityid').initialValue="";
          this.formList.find(item => item.fieldName === 'cityid').itemList = [];
          //清空县
          this.formList.find(item => item.fieldName === 'districtid').initialValue="";
          this.formList.find(item => item.fieldName === 'districtid').itemList=[];
        }
        if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
          return;
        }
        //取省数据
        let rd = this.getRegionData();
        this.cityData = rd[provinceId].children;
        let cl = this.createSubRegionList(this.cityData);
        this.formList.find(item => item.fieldName === 'cityid').itemList = cl;
      },
      //初始化所在县数据
      async initTown(cityId,flag = true){
        if(flag){
          //清空县
          this.formList.find(item => item.fieldName === 'districtid').initialValue="";
          this.formList.find(item => item.fieldName === 'districtid').itemList=[];
        }
        if(!cityId || cityId==null || typeof(cityId)=='undefined'){
          return;
        }
        let td = this.cityData[cityId].children;
        let tl = this.createSubRegionList(td);
        const list = this.formList.find(item => item.fieldName === 'cityid').itemList
        const item = list.find(item=>item.value === cityId)
        if (item.text==='市辖区'){
          // 取省的名字
          const province = this.formList.find(item => item.fieldName === 'provinceid').itemList
          this.selectValue.cityName=province[0].text
        }else{
          this.selectValue.cityName=item.text
        }
        this.formList.find(item => item.fieldName === 'districtid').itemList = tl;
      },

      //初始化所在区数据
      async initDistrict(cityId) {
        if (!cityId || cityId == null || typeof cityId == 'undefined') {
          return;
        }
        let cl = this.district(cityId);
        //初始化区县，清除原值
        let district = this.formList.find(item => item.fieldName === 'districtid');
        district.itemList = cl;
        district.initialValue = '';
      },
      /*选择车辆信息回调 */
      selectVehicleFun(arr) {
        if (arr){
          this.formList.find(item => item.fieldName === 'vin').initialValue=arr[0].vin
        }
        this.visbleVehicle = false
      },
      openvehicle(){
        this.visbleVehicle = true
      },
      clearSelectModel(){
        this.formList.find(item => item.fieldName === 'vin').initialValue=''
      }
    }
  };
</script>

<style scoped>

</style>
